#==========和弦图============
#2023/08/18创建 Ivan Yan
#2023/8/21 修改绘图过程，优化显示，排序，颜色分配。

#================================
 

library(circlize)
library(viridis)
library(reshape2)
library(dplyr)

library(readxl)
#导入数据
dataraw <- read_excel("当前申请（专利权）人区域到受理局流向图.xlsx", 
                                      col_types = c("text", "numeric", "numeric", 
                                                        "numeric", "numeric", "numeric", 
                                                       "numeric", "numeric", "numeric", 
                                                        "numeric", "numeric", "numeric", 
                                                       "numeric", "numeric", "numeric", 
                                                       "numeric", "numeric", "numeric", 
                                                       "numeric", "numeric", "numeric"))

df<-dataraw
#精简数据集
df<-df[1:10,1:11]



#=========排序================
#排序算法1：仅按行求和，即按From求和。
#df_sum<-apply(df[,2:ncol(df)],2,sum) #按列求和，用于后续排序
#df_sum<-apply(df[,2:ncol(df)],1,sum)#按行求和，用于后续排序

#排序算法2：按行求和，按列求和，以行为准，对相同名称再求和，修正行求和结果。
df_sum_row_group<-apply(df[,2:ncol(df)],1,sum)#按行求和
df_sum_col_group<-apply(df[,2:ncol(df)],2,sum) #按列求和

df_sum_row_group_dataframe<-data.frame(from=df[,1],sum_row=df_sum_row_group)
colnames(df_sum_row_group_dataframe)[1]<-"from"
df_sum_col_group_dataframe<-data.frame(to=colnames(df)[2:ncol(df)],sum_col=df_sum_col_group)

df_sum_row_col_match<-df_sum_row_group_dataframe%>%
                        left_join(df_sum_col_group_dataframe,by=c("from"="to"))
df_sum_row_col_match[is.na(df_sum_row_col_match)]<-0
df_row_summarise<-df_sum_row_col_match%>%
                  mutate(sum=sum_row+sum_col)


#继续计算，排序即可


order<-sort(df_row_summarise$sum,index.return=TRUE,decreasing =TRUE)#返回对象包含排序后的向量，以及排序的索引。

df_melt <- melt(df,id.vars = '当前申请(专利权)人区域')
colnames(df_melt)<-c("from","to","value")

#df_melt$to<-factor(df_melt$to,levels=df$'当前申请(专利权)人区域'[order$ix],order=TRUE)
df_melt$from<-factor(df_melt$from,levels=df$'当前申请(专利权)人区域'[order$ix],order=TRUE)

df_melt<-dplyr::arrange(df_melt,from)

#计算节点数量，用于后续分配颜色
nodes<-c(c(t(df[,1])),colnames(df)[2:ncol(df)])
nodes<-unique(nodes)

#颜色分配
mycolor <- viridis(length(nodes), alpha = 1, begin = 0, end = 1, option = "D")
#names(mycolor) <-df$'nodes'
mycolor_rnd<-sample(mycolor,length(nodes))

circos.clear()
circos.par(start.degree = 90, gap.degree = 4, track.margin = c(-0.1, 0.1), points.overflow.warning = FALSE)
par(mar = rep(0, 4))

chordDiagram(
  x = df_melt,
  grid.col = mycolor_rnd,
  transparency = 0.25,
  directional = 1,
  direction.type = c("arrows", "diffHeight"),
  diffHeight = -0.04,
  annotationTrack = "grid",
  annotationTrackHeight = c(0.05, 0.1),
  link.arr.type = "big.arrow",
  link.sort = TRUE,
  link.largest.ontop = TRUE)

# 添加数据标签和坐标轴
circos.trackPlotRegion(
  track.index = 1,
  bg.border = NA,
  panel.fun = function(x, y) {
    xlim = get.cell.meta.data("xlim")
    sector.index = get.cell.meta.data("sector.index")

     #添加坐标轴
    circos.axis(
      h = "top",
      major.at = seq(from = 0, to = xlim[2], by = ifelse(test = xlim[2]>400, yes = 200, no = xlim[2])),
      #minor.ticks = 1,
      major.tick.percentage = 0.1,
      labels.niceFacing = FALSE,
      labels.cex =0.5)
    
    # 添加数据标签
    circos.text(
      x = mean(xlim),
      y = 3.2,
      labels = sector.index,
      facing = "bending",
      cex = 0.5
    )
  }
)
